package handler

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"shop/goods-srv/global"
	"shop/goods-srv/model"
	brandproto "shop/goods-srv/proto"
)

type BrandService struct{}

func BrandModelToResponse(brand model.Brands) brandproto.BrandInfoResponse {
	brandResp := brandproto.BrandInfoResponse{
		Id:   brand.ID,
		Name: brand.Name,
		Logo: brand.Logo,
	}
	return brandResp
}

func (b *BrandService) BrandList(ctx context.Context, req *brandproto.BrandFilterRequest) (*brandproto.BrandListResponse, error) {
	var brand []model.Brands
	pn := int(req.Pages)
	psize := int(req.PagePreNums)
	zap.S().Info("brand列表")
	result := global.Db.Scopes(Paginate(pn, psize)).Find(&brand)
	zap.S().Info("brand列表", result.RowsAffected)
	if result.Error != nil {
		zap.S().Fatalf("brand列表数据获取失败%s", result.Error)
	}
	resp := &brandproto.BrandListResponse{}
	for _, banner := range brand {
		brandInfoResponse := BrandModelToResponse(banner)
		resp.Data = append(resp.Data, &brandInfoResponse)
	}
	return resp, nil
}
func (b *BrandService) CreateBrand(ctx context.Context, req *brandproto.BrandRequest) (*brandproto.BrandInfoResponse, error) {
	var brand model.Brands
	if req.Name != "" {
		brand.Name = req.Name
	}
	if req.Logo != "" {
		brand.Logo = req.Logo
	}

	create := global.Db.Create(&brand)
	if create.Error != nil {
		status.Errorf(codes.Canceled, "创建失败")
	}
	return &brandproto.BrandInfoResponse{
		Id:   brand.ID,
		Name: brand.Name,
		Logo: brand.Logo,
	}, nil
}
func (b *BrandService) UpdateBrand(ctx context.Context, req *brandproto.BrandRequest) (*emptypb.Empty, error) {
	var brand model.Brands
	brandInfo := global.Db.First(&brand)
	if brandInfo.Error != nil {
		zap.S().Fatalf("brand信息数据获取失败%s", brandInfo.Error)
	}
	if req.Name != "" {
		brand.Name = req.Name
	}
	if brand.Logo != "" {
		brand.Logo = req.Logo
	}

	re := global.Db.Save(&brand)
	fmt.Println(re.Error)
	fmt.Println(re.RowsAffected)
	return &emptypb.Empty{}, nil
}
func (b *BrandService) DeleteBrand(ctx context.Context, req *brandproto.BrandRequest) (*emptypb.Empty, error) {
	var brand model.Brands
	brandInfo := global.Db.First(&brand)
	if brandInfo.Error != nil {
		zap.S().Fatalf("brand信息数据获取失败%s", brandInfo.Error)
	}
	if req.Id == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "brand id not specified")
	}
	del := global.Db.Delete(&brand)
	if del.Error != nil {
		return nil, status.Errorf(codes.Canceled, "brand 删除失败")
	}
	return &emptypb.Empty{}, nil
}
